package com.future.WebSocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.future.allUtils.utils.SecurityUtils;
import com.future.domain.ChatMessage;
import com.future.domain.DTO.ChatReponseDTO;
import com.future.domain.DTO.MessageDTO;
import com.future.domain.LoginUserDetails;
import com.future.domain.User;
import com.future.mapper.ChatMessageMapper;
import com.future.mapper.ChatRoomMemberMapper;
import com.future.mapper.UserMapper;
import com.future.service.ChatMemberService;
import com.future.service.ChatMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;

/**
 * 私信
 */
@Component
@Slf4j
public class PravateChatstrategy implements Chatstrategy{
    @Autowired
    private WebSocketSessionManager webSocketSessionManager;
    @Autowired
    private ChatRoomMemberMapper chatRoomMemberMapper;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private ChatMessageService messageService;
    @Autowired
    private UserMapper userMapper;
    @Override
    public void handleMessage(WebSocketSession session, ChatMessage message) {
        //把消息存入数据库
        Long roomId=message.getChatRoomId();
        Long senderId=message.getSenderId();
        Long receiverId= getReceiverIdFromChatRoom(roomId, senderId);
        Long userId = (Long) session.getAttributes().get("userId");
        User user = userMapper.selectById(userId);
        if(receiverId==null||senderId==null)
        {
            log.error("消息参数不完整");
            return;
        }
        if(receiverId==null)
        {
            log.error("接收用户为空");
            return;
        }
        try {
            // 保存到数据库和缓存
            MessageDTO messageDTO=new MessageDTO();
            BeanUtils.copyProperties(message, messageDTO);
            messageDTO.setSenderName(user.getUsername());
            messageDTO.setSenderAvatar(user.getAvatar());
            messageDTO.setSenderId(senderId.toString());
            messageDTO.setChatRoomId(roomId.toString());
            messageService.saveChatMessage(messageDTO);
            // 尝试实时发送消息给接收者
           webSocketSessionManager.broadcastToRoom(roomId,messageDTO);
            // 发送成功响应给发送者
            ChatReponseDTO successResponse = new ChatReponseDTO(messageDTO.getId(), "消息发送成功");
            sendJsonResponse(session, successResponse);
        } catch (Exception e) {
            log.error("发送消息失败，sender:{} -> receiver:{}", senderId, receiverId, e);
            // 发送失败响应给发送者
            ChatReponseDTO errorResponse = new ChatReponseDTO(
                    message != null ? message.getId().toString() : "unknown",
                    "消息发送失败，请重试"
            );
            sendJsonResponse(session, errorResponse);
            // 消息发送失败，但由于已保存到数据库，用户上线后仍能收到
        }


    }
    private Long getReceiverIdFromChatRoom(Long roomId,Long senderId) {
        List<Long> members = chatRoomMemberMapper.selectUserIdByRoomId(roomId);
        return members.stream()
                .filter(memberId -> !memberId.equals(senderId))
                .findFirst()
                .orElseThrow(() -> new IllegalStateException("私聊房间必须包含至少2个成员"));

    }
    private void sendJsonResponse(WebSocketSession session, ChatReponseDTO response) {
        try {
            if (session != null && session.isOpen()) {
                String jsonResponse = objectMapper.writeValueAsString(response);
                session.sendMessage(new TextMessage(jsonResponse));
            } else {
                log.warn("WebSocketSession 已关闭或为空，无法发送响应");
            }
        } catch (Exception e) {
            log.error("构造或发送 JSON 响应失败", e);
        }
    }
}
